package com.kimehwa.chapter2.Container2;

import java.util.HashSet;
import java.util.Set;

/**
 * @author xiaodongguan
 * @date 2022/02/22 23:51
 * @description 用匿名静态内部类进行处理 可以让加水操作成为常数操作
 **/
public class Container3 {


    private Group group;

    public void addWater(double amount) {
        double average = amount / group.members.size();
        group.amountPerContainer += average;
    }

    public void connectTo(Container3 other) {
        if (group == other.group) return;
        // 先找到平均的钱
        double average = (this.group.amountPerContainer * this.group.members.size()
                + other.group.amountPerContainer * other.group.members.size()) / (this.group.members.size() +
                other.group.members.size());
        group.amountPerContainer = average;
        group.members.addAll(other.group.members);

        for (Container3 c : other.group.members) {
            c.group = group;
        }

    }


    private static class Group {
        double amountPerContainer;
        Set<Container3> members;

        Group(Container3 c) {
            this.members = new HashSet<>();
            members.add(c);
        }
    }
}
